package org.amphiprion.rfreplayanalyser.ui.race;

import java.util.HashMap;

import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

import org.amphiprion.rfreplayanalyser.util.TimingUtil;

@SuppressWarnings("serial")
public class DriverListTableModel implements TableModel {
	private HashMap<Long, DriverItem> drivers = new HashMap<Long, DriverItem>();
	private static String[] columnNames = { "o", "Pos", "Name", "Lap" };
	private long[] ranking;
	private RaceProvider raceProvider;
	private int nbDrivers = 0;

	public DriverListTableModel(RaceProvider raceProvider) {
		this.raceProvider = raceProvider;
	}

	public void addDriver(DriverItem di) {
		drivers.put(di.driverId, di);
	}

	public void setDriverRank(long[] ranking) {
		this.ranking = ranking;
		nbDrivers = 0;
		for (long id : ranking) {
			if (id != 0) {
				nbDrivers++;
			}
		}
	}

	@Override
	public void addTableModelListener(TableModelListener arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public Class<?> getColumnClass(int index) {
		if (index == 0) {
			return Boolean.class;
		}

		return String.class;
	}

	@Override
	public int getColumnCount() {
		return columnNames.length;
	}

	@Override
	public String getColumnName(int col) {
		return columnNames[col];
	}

	@Override
	public int getRowCount() {
		return nbDrivers;
	}

	@Override
	public Object getValueAt(int row, int col) {
		DriverItem di = getDriverAtPos(row);
		switch (col) {
		case 0:
			return di.shown;
		case 1:
			return row + 1;
		case 2:
			if (di == null) {
				return "UNKNOW ID";
			}
			return di.driverName + " (" + di.driverId + ")";
		case 3:
			if (di == null) {
				return "UNKNOW ID";
			}
			String etat = null;
			if (di.currentLap == -1) {
				etat = "Not in Race";
			} else {
				if (di.running) {
					etat = "" + di.currentLap + " (" + TimingUtil.getTimeAsLaptimeString(di.currentLapTime) + ")";
				} else {
					etat = di.notRunningReason;
				}
			}
			return etat;
		default:
			break;
		}
		return "???";
	}

	/**
	 * First position is 0
	 * 
	 * @param row
	 * @return
	 */
	public DriverItem getDriverAtPos(int row) {
		long driverId = ranking[row];
		return drivers.get(driverId);
	}

	@Override
	public boolean isCellEditable(int row, int col) {

		return col == 0;
	}

	@Override
	public void removeTableModelListener(TableModelListener arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setValueAt(Object value, int row, int col) {
		if (col == 0) {
			DriverItem di = getDriverAtPos(row);
			di.shown = (Boolean) value;
			raceProvider.driverItemUpdated(di);
		}
	}
}
